package com.helen.ui.order;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.helen.adapter.CommitOrderListAdapter;
import com.helen.db.UserHelper;
import com.helen.entity.AddressListEntity;
import com.helen.entity.CommitPaidEntity;
import com.helen.entity.CommitProductEntity;
import com.helen.entity.CouponsEntity;
import com.helen.event.InfoEnent;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.ui.address.AddressListActivity;
import com.helen.ui.coupons.CouponsActivity;
import com.helen.utils.JsonUtil;
import com.helen.utils.MyLog;
import com.helen.utils.tiputils.MToast;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2018/5/24.
 * 提交订单
 */

public class CommitOrderActivity extends BaseActivity {
    private static final int LOCATION = 0x11;
    private static final int DAIJIN = 0x12;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_detail_address)
    TextView tvDetailAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.tv_product_price)
    TextView tvProductPrice;
    @BindView(R.id.tv_discount_amount)
    TextView tvDiscountAmount;
    @BindView(R.id.tv_jinbao)
    TextView tvJinbao;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.tv_all_price)
    TextView tvAllPrice;
    @BindView(R.id.tv_product_count)
    TextView tvProductCount;
    @BindView(R.id.tv_commit_order)
    TextView tvCommitOrder;

    @BindView(R.id.rel_jinbao)
    RelativeLayout relJinbao;
    @BindView(R.id.view_jinbao_line)
    View viewJinbaoLine;
    @BindView(R.id.rel_daijin)
    RelativeLayout relDaijin;
    @BindView(R.id.view_daijin_line)
    View viewDaijinLine;


    private List<CommitProductEntity> commitProductEntityList = new ArrayList<>();
    private CommitOrderListAdapter commitOrderListAdapter;
    private AddressListEntity addressListEntity;

    //   代金券
    private CouponsEntity couponsEntity = new CouponsEntity();
    private int mPosition = -1;
    private TextView tvItemDaijin;

    private double mProductPrice;//商品价格
    private int mJinBaoPrice;//金宝
    private double mDaiJinPrice;//代金券
    private double mExpressprice;//运费
    private double mTotalPrice;//合计
    private double mAllPrice;//总价

    private double daiJin;//代金券
    private int jinBao;//金宝

    private boolean isShopCar = false;//是否来自购物车

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_commit_order;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.sure_order);
        isShopCar = getIntent().getBooleanExtra("isShopCar", false);
        commitProductEntityList = (List<CommitProductEntity>) getIntent().getSerializableExtra("commitProductEntityList");
        for (int i = 0; i < commitProductEntityList.size(); i++) {
            mProductPrice += commitProductEntityList.get(i).getProductPrice() * commitProductEntityList.get(i).getCount();
            mExpressprice += commitProductEntityList.get(i).getExpressprice();
            jinBao += commitProductEntityList.get(i).getJinbao();
            daiJin += commitProductEntityList.get(i).getDaijin();
        }

        if (jinBao == 0) {
            relJinbao.setVisibility(View.GONE);
            viewJinbaoLine.setVisibility(View.GONE);
        } else {
            relJinbao.setVisibility(View.VISIBLE);
            viewJinbaoLine.setVisibility(View.VISIBLE);
        }

        if (daiJin == 0) {
            relDaijin.setVisibility(View.GONE);
            viewDaijinLine.setVisibility(View.GONE);
        } else {
            relDaijin.setVisibility(View.VISIBLE);
            viewDaijinLine.setVisibility(View.VISIBLE);
        }


        commitOrderListAdapter = new CommitOrderListAdapter(R.layout.item_commit_order_list, commitProductEntityList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(CommitOrderActivity.this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvList.setLayoutManager(linearLayoutManager);
        rvList.setAdapter(commitOrderListAdapter);

        commitOrderListAdapter.setOnItemDaiJinListener(new CommitOrderListAdapter.OnSetDaiJinListener() {
            @Override
            public void setOnDaiJinListener(int position, CommitProductEntity commitProductEntity, TextView tvDaijin) {
                mPosition = position;
                tvItemDaijin = tvDaijin;
                Intent ti3 = new Intent(CommitOrderActivity.this, CouponsActivity.class);
                ti3.putExtra("isCheckBox", true);
                ti3.putExtra("couponsId", commitProductEntity.getDiscardid());
                ti3.putExtra("couponsEntity", (Serializable) couponsEntity);
                ti3.putExtra("productPrice", commitProductEntity.getProductPrice());
                startActivityForResult(ti3, DAIJIN);
            }
        });
        commitOrderListAdapter.setOnItemJinbaoListener(new CommitOrderListAdapter.OnSetJinbaoListener() {
            @Override
            public void setOnJinbaoListener(List<CommitProductEntity> commitProductEntityList) {
                settlement(commitProductEntityList);
            }
        });


        tvProductPrice.setText("￥" + mProductPrice);
        tvProductCount.setText("共" + commitProductEntityList.size() + "件商品");
        settlement(commitProductEntityList);
    }

    @Override
    protected void updateViews() {

    }


    //   结算
    private void settlement(List<CommitProductEntity> commitProductEntityList) {
        //        合计 = 商品价格 - 金宝 -代金券
        //        总价 = 商品价格 + 运费 - 金宝 -代金券
        mTotalPrice = 0.00;
        mAllPrice = 0.00;

        mDaiJinPrice = 0.00;
        mJinBaoPrice = 0;

        for (CommitProductEntity commitProductEntity : commitProductEntityList) {
            mDaiJinPrice += commitProductEntity.getmDaiJin();
        }

        for (CommitProductEntity commitProductEntity : commitProductEntityList) {
            mJinBaoPrice += commitProductEntity.getmJinbao();
        }

        tvDiscountAmount.setText("-￥" + mDaiJinPrice);
        tvJinbao.setText("-￥" + mJinBaoPrice);


        mTotalPrice = mProductPrice - mJinBaoPrice - mDaiJinPrice;
        mAllPrice = mProductPrice + mExpressprice - mJinBaoPrice - mDaiJinPrice;

        tvTotalPrice.setText("￥" + String.format("%.2f",mTotalPrice));
        tvAllPrice.setText("￥" + String.format("%.2f",mAllPrice));

    }


    @OnClick({R.id.ll_address, R.id.tv_commit_order})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_address:
                Intent ti = new Intent(this, AddressListActivity.class);
                ti.putExtra("backModel", true);
                startActivityForResult(ti, LOCATION);
                break;
            case R.id.tv_commit_order:
                if (addressListEntity == null) {
                    MToast.makeTextLong(CommitOrderActivity.this, "请选择收货地址").show();
                    return;
                }

                List<CommitPaidEntity> commitPaidEntityList = new ArrayList<>();
                for (int i = 0; i < commitProductEntityList.size(); i++) {
                    CommitPaidEntity commitPaidEntity = new CommitPaidEntity();
                    commitPaidEntity.setProductid(commitProductEntityList.get(i).getProductid());
                    commitPaidEntity.setCount(commitProductEntityList.get(i).getCount());
                    commitPaidEntity.setMemo(commitProductEntityList.get(i).getNote());
                    if (commitProductEntityList.get(i).getSpecid() != -1) {
                        commitPaidEntity.setSpecid(commitProductEntityList.get(i).getSpecid());
                    }
                    commitPaidEntity.setJinbao(commitProductEntityList.get(i).getmJinbao() + "");
                    commitPaidEntity.setDiscardid(commitProductEntityList.get(i).getDiscardid());
                    commitPaidEntityList.add(commitPaidEntity);
                }

                MyLog.e("yang", "json==" + new Gson().toJson(commitPaidEntityList));

                createOrder(addressListEntity.getId() + "", new Gson().toJson(commitPaidEntityList));

                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case LOCATION:
                    if (data != null) {
                        addressListEntity = (AddressListEntity) data.getSerializableExtra("addressListEntity");
                        tvName.setText("姓名: " + addressListEntity.getName());
                        tvPhone.setText(addressListEntity.getPhone());
                        tvDetailAddress.setText("详细地址: " + addressListEntity.getCity() + addressListEntity.getDetail());
                    }
                    break;
                case DAIJIN:
                    couponsEntity = null;
                    couponsEntity = (CouponsEntity) data.getSerializableExtra("couponsEntity");
                    if (couponsEntity != null) {
                        commitProductEntityList.get(mPosition).setDiscardid(couponsEntity.getId());
                        tvItemDaijin.setText(couponsEntity.getName());
                        commitProductEntityList.get(mPosition).setmDaiJin(couponsEntity.getMoney());
                    } else {
                        tvItemDaijin.setText("");
                        tvItemDaijin.setHint("请选择代金券");
                        commitProductEntityList.get(mPosition).setDiscardid(0);
                        commitProductEntityList.get(mPosition).setmDaiJin(0);
                    }
                    settlement(commitProductEntityList);
                    break;
            }
        }
    }


    private void createOrder(String addressid, String orderlist) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("userid", UserHelper.getInstance().getloginEntity(CommitOrderActivity.this).getId() + "");
        params.put("addressid", addressid);
        params.put("orderlist", orderlist);
        params.put("isShopCar", isShopCar+"");

        EasyHttp.post(Constants.API_JSONAPI_CREATEORDER)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "提交订单失败==" + e.toString());
                        MToast.makeTextShort(CommitOrderActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.e("yang", "提交订单==" + result);
                        int code = JsonUtil.getJsonValuesInt(result, "code");
                        String msg = JsonUtil.getJsonValuesString(result, "msg");
                        if (code == 0) {
                            if(isShopCar){
                                EventBus.getDefault().post(new InfoEnent(InfoEnent.ADD_CAR_SUCCESS));
                            }
                            Intent ti = new Intent(CommitOrderActivity.this, PaidOrderActivity.class);
                            ti.putExtra("orderid", JsonUtil.getJsonValuesString(result, "orderid"));
                            ti.putExtra("allPrice", mAllPrice + "");
                            ti.putExtra("fromType", 2);
                            startActivity(ti);
                            finish();
                        } else {
                            MToast.makeTextShort(CommitOrderActivity.this, msg).show();
                        }

                    }
                });
    }

}
